<?php

namespace Tbf\Bundle\TestBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;

/**
 * This is the class that loads and manages your bundle configuration
 *
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
 */
class TbfTestExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $container->setParameter('tbf_test.resources.config_dir',__DIR__.'/../Resources/config');

        $cache_dir = $container->getParameterBag()->resolveValue('%kernel.cache_dir%/tbf_test');
        $container->setParameter('tbf_test.cache_dir',$cache_dir);

        if (!is_dir($cache_dir) && false === @mkdir($cache_dir, 0777, true)) {
            throw new \RuntimeException(sprintf('Could not create cache directory "%s".', $cache_dir));
        }

        if (!empty($config['host'])) {
            $container->setParameter('tbf_test.host', $config['host']);
        }
        if (!empty($config['ajax_client_config'])) {
            $container->setParameter('tbf_test.ajax_client_config', $config['ajax_client_config']);
        }

        if ($container->getParameter('kernel.environment')==='test') {
            $container->setDefinition('tbf.clock',
                new Definition('Tbf\Bundle\TestBundle\Service\PersistChangeableClock')
            )->addArgument('%tbf_test.cache_dir%/clock.json');

            $container->setDefinition('tbf.listener.text_exception',
                new Definition('Tbf\Bundle\TestBundle\Listener\TextExceptionListener')
            )->addTag('kernel.event_subscriber');
        }
        if (!empty($config['is_real_http'])) {
            $container->setAlias('tbf_test.ajax','tbf_test.ajax.real');
            $container->setAlias('tbf_test.session','tbf_test.session.real');
        }else{
            $container->setAlias('tbf_test.ajax','tbf_test.ajax.symfony');
            $container->setAlias('tbf_test.session','tbf_test.session.symfony');
        }
    }
}
